package com.src.xyzk_personal;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.Service;
import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.src.xyzk_personal.R;
import com.src.xyzk_personal.EOL.DbAdapter;
import com.src.xyzk_personal.EOL.DbAdapter.TableData;
import com.src.xyzk_personal.EOL.DbAdapter.TableMain;
import com.src.xyzk_personal.config.Common;
import com.src.xyzk_personal.config.MyProgressBar;
import com.src.xyzk_personal.config.ServerSocket;
import com.src.xyzk_personal.config.WifiAdmin;

public class UpdateDataActivity extends Activity {
    private static String TAG = "UpdateDataActivity";
    Context context = UpdateDataActivity.this;
    //锁定屏幕
    private PowerManager powerManager = null;
    private WakeLock wakeLock = null;

    private MyProgressBar m_progress = null;
    private TextView m_showtext = null;
    private Button m_update = null;

    private UpdateThread m_thread = null;

    //设置
    private Spinner m_printselect = null;    //下拉菜单
    private ArrayList<String> m_printarray = null;
    private ArrayAdapter<String> m_printadapter = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.updatedata_activity);
        //锁定屏幕初始化
        powerManager = (PowerManager) this.getSystemService(Service.POWER_SERVICE);
        wakeLock = this.powerManager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My Lock");
        //是否需计算锁的数量
        wakeLock.setReferenceCounted(false);
        //progress
        m_progress = (MyProgressBar) findViewById(R.id.update_progress);
        m_showtext = (TextView) findViewById(R.id.update_show_text);
        m_update = (Button) findViewById(R.id.update_but_update);
        m_update.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                m_update.setClickable(false);
                if (GetServerConnect() == true) {
                    m_thread = new UpdateThread();
                    m_thread.start();
                }
            }
        });
        m_printselect = (Spinner) findViewById(R.id.update_print_select);
        m_printarray = new ArrayList<String>();
        for (int i = 1; i <= Common.Printnumber; i++)
            m_printarray.add(getString(R.string.update_tip_txt1) + i);
        m_printadapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, m_printarray);
        //设置下拉风格
        m_printadapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
        m_printselect.setAdapter(m_printadapter);
        m_printselect.setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> arg0, View arg1,
                                       int arg2, long arg3) {
                // TODO Auto-generated method stub
                Common.Printnum = arg2 + 1;
                SharedPreferences settings = getSharedPreferences(getString(R.string.app_name), Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = settings.edit();
                editor.putInt("Print", Common.Printnum);
                editor.commit();
            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
                // TODO Auto-generated method stub

            }
        });
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        //从缓存获取打印机设置
        SharedPreferences settings = getSharedPreferences(getString(R.string.app_name), Context.MODE_PRIVATE);
        //3.生成一个保存编辑变量
        int printnum = settings.getInt("Print", 1);
        m_printselect.setSelection(printnum - 1, true);
        m_printadapter.notifyDataSetChanged();
        //请求常亮
        wakeLock.acquire();
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        //取消屏幕常亮
        wakeLock.release();
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        if (m_thread != null) m_thread.close();
        super.onDestroy();
    }

    private final static int MSG_SHOW_TEXT_ID = 101;
    private final static int MSG_SHOW_TEXT = 102;
    private final static int MSG_INIT_PROGRESS = 103;
    private final static int MSG_SET_PROGRESS = 104;
    private final static int MSG_END_PROGRESS = 105;
    private Handler m_handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_SHOW_TEXT_ID:
                    m_showtext.setText(msg.arg1);
                    m_showtext.invalidate();
                    break;
                case MSG_SHOW_TEXT:
                    m_showtext.setText((CharSequence) msg.obj);
                    m_showtext.invalidate();
                    break;
                case MSG_INIT_PROGRESS:
                    m_progress.setMax(msg.arg1);
                    m_progress.invalidate();
                    break;
                case MSG_SET_PROGRESS:  //arg1 -- 进度
                    m_progress.setProgress(msg.arg1);
                    m_progress.invalidate();
                    break;
                case MSG_END_PROGRESS:    //结束
                    m_update.setClickable(true);
                    break;
                default:
                    break;
            }
        }
    };

    private boolean GetServerConnect() {
        //检查连接状况
        m_handler.obtainMessage(MSG_SHOW_TEXT_ID, R.string.update_msg_tip3, 0).sendToTarget();
        WifiAdmin wifi = new WifiAdmin(context);
        if (wifi.getState() < 2) //已经关闭，则打开
        {
            Toast.makeText(context, R.string.main_tip_text7, Toast.LENGTH_SHORT).show();
            return false;
        }
        String name = wifi.getWifiConnectSSID();
        if (name != null) {
            if (name.equals(Common.ServerName) == false) {
                m_handler.obtainMessage(MSG_SHOW_TEXT_ID, R.string.update_msg_tip4, 0).sendToTarget();
                return false;
            }
        } else {
            m_handler.obtainMessage(MSG_SHOW_TEXT_ID, R.string.update_msg_tip2, 0).sendToTarget();
            return false;
        }
        return true;
    }

    //上传线程
    public class UpdateThread extends Thread {
        ServerSocket m_com = null;
        public boolean exit = false;
        DbAdapter m_db = null;

        public UpdateThread() {
            // TODO Auto-generated constructor stub
            m_db = new DbAdapter(context);
            m_com = new ServerSocket();
            exit = false;
        }

        void close() {
            m_handler.obtainMessage(MSG_END_PROGRESS).sendToTarget();
            exit = true;
            if (m_com != null)
                m_com.close();
            if (m_db != null)
                m_db.close();
        }

        @Override
        public void run() {
            // TODO Auto-generated method stub
            super.run();
            if (exit) return;
            //连接服务器
            if (m_com.ConnectServer(Common.Server_IP, Common.Server_PORT) == false) //连接失败！
            {
                m_handler.obtainMessage(MSG_SHOW_TEXT_ID, R.string.update_msg_tip5, 0).sendToTarget();
                close();
                return;
            }
            //查询数据库有多少条数据需要上传
            m_handler.obtainMessage(MSG_SHOW_TEXT_ID, R.string.update_msg_tip1, 0).sendToTarget();
            m_db.open();
            List<Map<String, Object>> uplist = m_db.querymainTable(TableMain.update + " =?", new String[]{"0"}, null, null);
            if (uplist == null) {
                m_handler.obtainMessage(MSG_SHOW_TEXT_ID, R.string.update_msg_tip6, 0).sendToTarget();
                close();
                return;
            }
            int size = uplist.size();
            if (size == 0) {
                m_handler.obtainMessage(MSG_SHOW_TEXT_ID, R.string.update_msg_tip6, 0).sendToTarget();
                close();
                return;
            }
            if (exit) return;
            //开始上传,设置进度条
            m_handler.obtainMessage(MSG_INIT_PROGRESS, size, 0).sendToTarget();
            m_handler.obtainMessage(MSG_SHOW_TEXT_ID, R.string.update_msg_tip7, 0).sendToTarget();
            Sleep(Common.waittime);
            m_handler.obtainMessage(MSG_SET_PROGRESS, 0, 0).sendToTarget();
            int i = 0;
            for (i = 0; i < size; i++) {
                if (exit) return;
                //整理上传的数据
                ContentValues cv = new ContentValues();
                cv.put(TableMain.vin, uplist.get(i).get(TableMain.vin).toString());
                cv.put(TableMain.cartype, uplist.get(i).get(TableMain.cartype).toString());
                cv.put(TableMain.station, uplist.get(i).get(TableMain.station).toString());
                cv.put(TableMain.timestart, uplist.get(i).get(TableMain.timestart).toString());
                cv.put(TableMain.timeend, uplist.get(i).get(TableMain.timeend).toString());
                cv.put(TableMain.result, uplist.get(i).get(TableMain.result).toString());
                cv.put(TableMain.printdata, uplist.get(i).get(TableMain.printdata).toString());
                cv.put(TableMain.device, uplist.get(i).get(TableMain.device).toString());
                cv.put(TableMain.appversion, uplist.get(i).get(TableMain.appversion).toString());
                if (m_com.SendDataToServer("1:" + new String(cv.toString())) == false) {
                    m_handler.obtainMessage(MSG_SHOW_TEXT_ID, R.string.update_msg_tip9, 0).sendToTarget();
                    close();
                    return;
                }
                Sleep(Common.waittime);
                //传递详细数据
                List<Map<String, String>> listdata = m_db.queryDataTable(uplist.get(i).get(TableMain.vin).toString(),
                        TableData.testnum + " =?", new String[]{uplist.get(i).get(TableMain.testnum).toString()}, null, null);
                //分开传
                List<Map<String, String>> listcache = null;
                int every_num = 20;
                int datanum = listdata.size() / every_num;
                for (int k = 0; k < datanum; k++) {
                    listcache = listdata.subList(k * every_num, (k + 1) * every_num);
//  					for(int s = 0; s < listcache.size(); s ++) //去除空格
//  					{
//  						if(listcache.get(s).get(key))
//  					}
                    String updata = "2:" + listcache.size() + ":" + new String(listcache.toString());
                    if (m_com.SendDataToServer(updata) == false) {
                        m_handler.obtainMessage(MSG_SHOW_TEXT_ID, R.string.update_msg_tip9, 0).sendToTarget();
                        close();
                        return;
                    }
                    Sleep(Common.waittime * 20);
                }
                if ((listdata.size() % every_num) > 0) //最后一点没传完
                {
                    listcache = listdata.subList(datanum * every_num, listdata.size());
                    String updata = "2:" + listcache.size() + ":" + listcache.toString();
                    if (m_com.SendDataToServer(updata) == false) {
                        m_handler.obtainMessage(MSG_SHOW_TEXT_ID, R.string.update_msg_tip9, 0).sendToTarget();
                        close();
                        return;
                    }
                }
                Sleep(Common.waittime * 20);
                //写回数据库标记
                m_db.UpdataTableUpdate(TableMain.Name, uplist.get(i).get(TableMain.vin).toString(),
                        (Integer) uplist.get(i).get(TableMain.testnum), 1);
                Sleep(1);
                m_handler.obtainMessage(MSG_SET_PROGRESS, i + 1, 0).sendToTarget();
            }
            if (i > 0 && i >= size)
                m_handler.obtainMessage(MSG_SHOW_TEXT_ID, R.string.update_msg_tip8, 0).sendToTarget();
            m_com.SendDataToServer("0");
            close();
        }

        private void Sleep(int time) {
            try {
                sleep(time);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}
